//
//  GoodDetailController.m
//  CenturyCity
//
//  Created by beisheng03 on 2017/12/8.
//  Copyright © 2017年 beisheng. All rights reserved.
//

#import "GoodDetailController.h"
#import "GoodsCycleImageCell.h"
#import "GoodsDetailMidCell.h"
#import "UserEvaluateCell.h"
#import "ShopCarController.h"
#import "GoodsDetailHeader.h"
#import "GoodsDetailSelectCell.h"
#import "GoodsDetailHTMLCell.h"
#import "GoodsDetailModel.h"
#import "PopoverController.h"
#import "PopoverAnimDelegate.h"
#import "OrderSureFirstVC.h"
#import "GoodsDetailBottom.h"
@interface GoodDetailController ()<CAAnimationDelegate>
/* */
@property (nonatomic, weak) UIView *headerView;

@property (nonatomic, weak) GoodsDetailBottom *bottomView;


@property (nonatomic, weak) UILabel *cntLabel;

@property (nonatomic, weak) UIImageView *animaCarView;

@property (nonatomic, weak) UIImage *animaImage;

@property (nonatomic, strong) PopoverAnimDelegate<UIViewControllerTransitioningDelegate> *animedDelegate;

/** <#note#> */
@property (nonatomic, weak) UIButton *addCarBtn;

@property (nonatomic,strong) UIBezierPath *myBezierPath;

@property (weak, nonatomic)  NSLayoutConstraint *cntLableH;
@property (weak, nonatomic)  NSLayoutConstraint *cntLableW;

/** <#note#> */
@property (nonatomic, weak) UIButton *leftBtn;


@property (nonatomic, weak) UIButton *rightBtn;

/** <#note#> */
@property (nonatomic, strong) NSString *myTag;

/**
 *  记录下最开始的y轴偏移量
 */
@property (nonatomic, assign) CGFloat oriOffsetY;

/** <#note#> */
@property (nonatomic, weak) UIView *navLineView;


/** <#note#> */
@property (nonatomic, weak) UILabel *titleLabel;


/** <#note#> */
@property (nonatomic, strong) GoodsDetailModel *dataModel;

@end


#define kHeadViewH 200

#define kHeadViewMinH 64

@implementation GoodDetailController{
    
    CALayer     *layer;
}


- (PopoverAnimDelegate<UIViewControllerTransitioningDelegate> *)animedDelegate{
    
    if (_animedDelegate == nil) {
        
        _animedDelegate = [[PopoverAnimDelegate alloc]init];
    }
    
    return  _animedDelegate;
}

//
- (UIView *)headerView{
    
    if (!_headerView){
        CGFloat viewH = IPhoneX ? 88 : 64;
        UIView *temp = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, viewH)];
        _headerView = temp;
        UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [leftBtn setImage:[UIImage imageNamed:@"goBackNew"] forState:UIControlStateNormal];
//        [leftBtn setImage:[UIImage imageNamed:@"goBackNew"] forState:UIControlStateHighlighted];
        
        [leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateNormal];
        [leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateHighlighted];
        leftBtn.backgroundColor = [UIColor clearColor];
        self.leftBtn = leftBtn;
        CGFloat btnY = IPhoneX ? 44 : 20;
        leftBtn.frame = CGRectMake(5, btnY, 44, 44);
//        leftBtn.backgroundColor = [UIColor greenColor];
        [_headerView addSubview:leftBtn];
        [leftBtn addTarget:self action:@selector(popCurrentController) forControlEvents:UIControlEventTouchUpInside];
        
        
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateNormal];
        [rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateHighlighted];
        rightBtn.frame = CGRectMake(KScreenW - 49, btnY, 44, 44);
        self.rightBtn = rightBtn;
        rightBtn.backgroundColor = [UIColor clearColor];
//        [_headerView addSubview:rightBtn];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, _headerView.height - 0.5, KScreenW, 0.5)];
        lineView.backgroundColor = [UIColor clearColor];
//        self.navLineView = lineView;
        
        
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"商品";
        titleLabel.textColor = [UIColor colorWithWhite:0 alpha:0];
        // 设置尺寸,尺寸最好根文字一样大
        // 自适应
        [titleLabel sizeToFit];
        CGFloat titleY = IPhoneX ? 44 : 20;
        
        titleLabel.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width - titleLabel.frame.size.width) * 0.5, titleY, titleLabel.frame.size.width, 44);
        
        self.titleLabel = titleLabel;

        [_headerView addSubview:self.navLineView];

        [_headerView addSubview:self.titleLabel];
        
        _headerView.hidden = YES;
        
       [self.view addSubview:temp];
    }
    
    return _headerView;
}




- (void)popCurrentController{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _oriOffsetY = 0;
    
    self.myTag = @"0";
    
    self.animaImage =  [[[SDWebImageManager sharedManager]imageCache]imageFromDiskCacheForKey:self.goodsModel.pic_cover_small];
//    self.animaImage = self.goodsModel.image;
    
    
    self.plainTableView.rowHeight = UITableViewAutomaticDimension;
    
    self.plainTableView.backgroundColor = [UIColor whiteColor];
    self.plainTableView.estimatedRowHeight = 500;
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsCycleImageCell class]) bundle:nil] forCellReuseIdentifier:[GoodsCycleImageCell identifierStr]];
    
     [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsDetailMidCell class]) bundle:nil] forCellReuseIdentifier:[GoodsDetailMidCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([UserEvaluateCell class]) bundle:nil] forCellReuseIdentifier:[UserEvaluateCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsDetailSelectCell class]) bundle:nil] forCellReuseIdentifier:[GoodsDetailSelectCell identifierStr]];
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsDetailHTMLCell class]) bundle:nil] forCellReuseIdentifier:[GoodsDetailHTMLCell identifierStr]];

    
    
    [self.plainTableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsDetailHeader class]) bundle:nil] forHeaderFooterViewReuseIdentifier:[GoodsDetailHeader identifierStr]];

    self.automaticallyAdjustsScrollViewInsets = NO;

//    CGFloat navH = IPhoneX ? 44 : 20;
    CGFloat tabbarH = IPhoneX ? 83 : 49;
    
    if (@available(iOS 11.0, *)) {
//        contentInsetAdjustmentBehavior属性也是用来取代automaticallyAdjustsScrollViewInsets属性的，推荐使用这种方式。
       self.plainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
       self.plainTableView.contentInset = UIEdgeInsetsMake(0, 0, tabbarH, 0);
        
    }else{
        
        self.plainTableView.contentInset = UIEdgeInsetsMake(0, 0, tabbarH, 0);

    }
    

    self.headerView.backgroundColor = [UIColor clearColor];
    
    
    
    [self setupBottomToolView];
    
//    self.phoneBtn.right = KScreenW;
//
//
//    self.phoneBtn.top = 100;
    
    
    MJWeakSelf
    self.plainTableView.mj_header = [XMGRefreshHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [self.plainTableView.mj_header beginRefreshing];
    
    
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didSelectGoodsSpec) name:@"DidSelectGoodsSpec" object:nil];

}

- (void)loadData{
    

    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    if (myViewModel.userIsLogin) {
        
        parameters[@"uid"] = myViewModel.user.uid;

    }
    
    parameters[@"goodsId"] = self.goodsModel.goods_id;
    
    NSLog(@"%@",self.goodsModel.goods_id);
    
    

    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:GET_METHOD URLPath:@"Good/getGoodsDetail" parameters:parameters completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            weakSelf.bottomView.hidden = NO;
            
            weakSelf.headerView.hidden = NO;
            
//            MYJSONSTR
            
            weakSelf.dataModel = [GoodsDetailModel mj_objectWithKeyValues:responseObject[@"data"]];
            
            weakSelf.dataModel.tag = @"0";
            
            [weakSelf setDisplayStr];
            
            if (weakSelf.dataModel.img_list.count > 0) {
                
                [weakSelf downloadImage];
                
            } else {
                
                [weakSelf.plainTableView.mj_header endRefreshing];
                
                
                [weakSelf.plainTableView reloadData];
            }
            


            
            
        } else {
            
            
            [weakSelf.plainTableView.mj_header endRefreshing];

            
            [SVProgressHUD showInfoWithStatus:error.domain];
            
            
            
        }
        
        
    }];
    
    
    
    
    
    
}


- (void)didSelectGoodsSpec{
    
    [self.plainTableView reloadData];
}


- (void)setDisplayStr{
    
    if (self.dataModel.spec_list.count > 0) {
        
        NSMutableString *tempStr = [NSMutableString string];
        
        for (GoodsSpecListModel *temp in self.dataModel.spec_list) {
            
            [tempStr appendString:temp.value.firstObject.spec_value_name];
            
            [tempStr appendString:@","];
            
        }
        
        NSString *lastStr =  [tempStr substringToIndex:tempStr.length - 1];
        
        self.dataModel.displayStr = lastStr;
        
    } else {
        
       self.dataModel.displayStr = self.dataModel.goods_name;
        
    }
    
    
    self.dataModel.selectSkuModel = self.dataModel.sku_list.firstObject;
    
    for (GoodsSkuListModel *skuModel in self.dataModel.sku_list) {
        skuModel.goods_image_url = self.goodsModel.pic_cover_small;
    }
    
    
    
}




- (void)downloadImage{
    
    dispatch_group_t group = dispatch_group_create();
    MJWeakSelf;
        dispatch_group_enter(group);
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:self.dataModel.img_list.firstObject] options:kNilOptions progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (image) {
                
                weakSelf.animaImage = image;
            }
            
            dispatch_group_leave(group);
            
        }];
    
  
    
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        [weakSelf.plainTableView.mj_header endRefreshing];
        
        [weakSelf.plainTableView reloadData];
        
        
        
    });
    
    
    
    
}






- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
    NSInteger count = [self calculateTotalGoodsCounts];
    if (count) {
        self.cntLabel.hidden = NO;
    }else{
        
        self.cntLabel.hidden = YES;
        
        return;
        
    }
    
    self.cntLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
    
    if (count > 9) {
        
        self.cntLableW.constant = 20;
        
    }else{
        
        self.cntLableW.constant = 14;
        
    }
    
    
    
}



#pragma mark - tableviewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        return 2;
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.dataModel == nil) {
        return 0;
    } else {
        
        if (section == 0) {
            return 2;
        } else {
            return 1;
        }
        
        
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            GoodsCycleImageCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[GoodsCycleImageCell identifierStr]];
            
            tableCell.model = self.dataModel;
            
            return tableCell;
            
        } else {
            
            GoodsDetailSelectCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[GoodsDetailSelectCell identifierStr]];
            
            tableCell.model = self.dataModel;
            
            return tableCell;
            

            
        }
    } else if (indexPath.section == 1){
        
        GoodsDetailHTMLCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[GoodsDetailHTMLCell identifierStr]];
        
        tableCell.model = self.dataModel;
        
        return tableCell;
        
    }else{
        
        UserEvaluateCell *tableCell = [tableView dequeueReusableCellWithIdentifier:[UserEvaluateCell identifierStr]];
        
        
        return tableCell;
    }
    
   
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return 0.00001;
    } else {
        return 52;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
      return nil;
        
    } else {
        
        
        GoodsDetailHeader *header = (GoodsDetailHeader *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:[GoodsDetailHeader identifierStr]];
        
        header.model = self.dataModel;
        
        return header;
        
        
        
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            [self  popSelectVC];
        }
    }
}




- (void)popSelectVC{
    
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Popover" bundle:[NSBundle mainBundle]];
    
    PopoverController *presentVC = [sb instantiateInitialViewController];
    
    presentVC.model = self.dataModel;
    
    presentVC.transitioningDelegate = self.animedDelegate;
    
    presentVC.modalPresentationStyle = UIModalPresentationCustom;
    /*自定义转场
     1.设置转场代理
     2.设置转场风格
     3.实现转场代理方法,返回一个继承UIPresentationController的负责转场的控制器
     */
    [self presentViewController:presentVC animated:YES completion:nil];
    
    
}



- (void)setupBottomToolView{
    
    
    GoodsDetailBottom *view = (GoodsDetailBottom *)[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([GoodsDetailBottom class]) owner:nil options:nil].firstObject;
    
    CGFloat bottomViewH = IPhoneX ? 83 : 49;
    
    view.hidden = YES;
    
    self.bottomView = view;
    view.frame = CGRectMake(0, KScreenH - bottomViewH, KScreenW, bottomViewH);
    
    [view.addCarBtn addTarget:self action:@selector(startAnimation) forControlEvents:UIControlEventTouchUpInside];
    
     [view.goToShopCarBtn addTarget:self action:@selector(thirdBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [view.atOnceBuyBtn addTarget:self action:@selector(gotoOderPage:) forControlEvents:UIControlEventTouchUpInside];

    
    
    
    self.addCarBtn = view.addCarBtn;
    
    self.animaCarView = view.carImageView;
    
    self.cntLableH = view.cntLabelH;
    self.cntLableW = view.cntLabelW;
    
    self.cntLabel = view.cntLabel;

    
    CGRect rect0 = CGRectMake((KScreenW * 0.5 - 87) * 0.5 + 19 , IPhoneX ? (KScreenH - 69) : (KScreenH - 35), 87, 21);
    CGRect rect1 = CGRectMake((KScreenW * 0.5 - 129) * 0.5, IPhoneX ? (KScreenH - 69) : (KScreenH - 35), 23, 22);
    CGFloat btnCentX = rect0.origin.x + rect0.size.width * 0.5;
    CGFloat btnCentY = rect0.origin.y + rect0.size.height * 0.5;
    CGFloat ImageCentX = rect1.origin.x + rect1.size.width * 0.5;
    CGFloat ImageCentY = rect1.origin.y + rect1.size.height * 0.5;

    self.myBezierPath = [UIBezierPath bezierPath];//CGPointMake(50, 300)
    [self.myBezierPath moveToPoint:CGPointMake(btnCentX,btnCentY)];
    [self.myBezierPath addQuadCurveToPoint:CGPointMake(ImageCentX,ImageCentY ) controlPoint:CGPointMake(ImageCentX + ((btnCentX - ImageCentX) * 0.5), rect0.origin.y > rect1.origin.y  ? rect1.origin.y - 66 : rect0.origin.y - 66)];
    
    [self.view addSubview:view];
    
  
}




- (void)gotoOderPage:(UIButton *)button{
    
    if (!(myViewModel.userIsLogin)) {
        
        [myViewModel.rootController login];
        
        return;
    }
    
    
        OrderSureFirstVC *orderVC = [[OrderSureFirstVC alloc]initWithStyle:UITableViewStyleGrouped];
        NSMutableString *strM = [NSMutableString string];
    
    
         GoodsSkuListModel *sub = self.dataModel.selectSkuModel;
         [strM appendString:sub.sku_id];
          [strM appendString:@":"];
          [strM appendString:@"1"];
    
         orderVC.goodsListStr = strM;
    
          orderVC.clearShopCar = @"NO";

    
        [self.navigationController pushViewController:orderVC animated:YES];
        
   
    
    
    
    
    //    NSLog(@"去支付");
}


- (void)thirdBtnDidClick:(UIButton *)button{
    
    //购物车
    ShopCarController *shopCarVC = [[ShopCarController alloc]init];
    
    shopCarVC.navigationItem.title = @"购物车";
    
    shopCarVC.type = @"goodsDetail";
    
    [self.navigationController pushViewController:shopCarVC animated:YES];
    
    
}



-(void)startAnimation
{
    
    if (!(myViewModel.userIsLogin)) {
        
        [myViewModel.rootController login];
        
        return;
    }
    
    
    
    
    
//    if ([self.model.item_info.sale_state isEqualToString:@"3"]) {
//
//        [CustomAlert showMessage:@"商品缺货,等待增加!"];
//
//
//        return;
//    }
//
//
//    if (self.model.item_info.stock_quantity.integerValue == self.model.count.integerValue ) {
//
//        [CustomAlert showMessage:@"此商品数量有限!"];
//
//        return;
//
//    }
//
    

    self.dataModel.selectSkuModel.goods_name = self.dataModel.goods_name;
    
    
    NSString *middelStr = [self.dataModel.displayStr stringByReplacingOccurrencesOfString:@"," withString:@" "];
    
    self.dataModel.selectSkuModel.middelText = self.dataModel.spec_list.count > 0 ? middelStr : nil;
    
    
    [self addGoodsWithModel:self.dataModel.selectSkuModel];
    
   
    
    
    if (!layer) {
        self.addCarBtn.enabled = NO;
        layer = [CALayer layer];
        layer.contents = (__bridge id)self.animaImage.CGImage;
        layer.contentsGravity = kCAGravityResizeAspectFill;
        layer.bounds = CGRectMake(0, 0, 6, 6);
        [layer setCornerRadius:CGRectGetHeight([layer bounds]) / 2];
        layer.masksToBounds = YES;
        //        layer.position =CGPointMake(50, 150);
        [self.view.layer addSublayer:layer];
    }
    [self groupAnimation];
}


-(void)groupAnimation
{
    
    self.addCarBtn.userInteractionEnabled = NO;
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = self.myBezierPath.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    
    
    CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    expandAnimation.duration = 0.3f;
    expandAnimation.fromValue = [NSNumber numberWithFloat:1.0f];
    expandAnimation.toValue = [NSNumber numberWithFloat:4.0f];
    expandAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3f;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:4.0f];
    narrowAnimation.duration = 0.3f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,expandAnimation,narrowAnimation];
    groups.duration = 0.6f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [layer addAnimation:groups forKey:@"group"];
}


-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    self.addCarBtn.userInteractionEnabled = YES;

    if (anim == [layer animationForKey:@"group"]) {
        self.addCarBtn.enabled = YES;
        [layer removeFromSuperlayer];
        layer = nil;
        NSInteger count = [self calculateTotalGoodsCounts];
        if (count) {
            self.cntLabel.hidden = NO;
        }else{
            
            self.cntLabel.hidden = YES;
            
        }
        
        CATransition *animation = [CATransition animation];
        animation.duration = 0.25f;
        
        self.cntLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
        if (count > 9) {
            self.cntLableW.constant = 20;
        }else{
            self.cntLableW.constant = 14;
        }
        
        [self.cntLabel.layer addAnimation:animation forKey:nil];
        
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.25f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:5];
        shakeAnimation.autoreverses = YES;
        [self.animaCarView.layer addAnimation:shakeAnimation forKey:nil];
    }
}



#pragma mark - scrollView代理方法
// 监听用户的滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    // 获取当前最新偏移量
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (offsetY < 0) {
        
        if ([self.myTag isEqualToString:@"0"]) {
            return;
        }
        
        offsetY = -offsetY;
        
        // 计算下最新偏移量和最初偏移量的差值
        // 就是用户滚动的区域
        CGFloat delta = offsetY - _oriOffsetY;
        
        // 移动头部视图
        //    _headViewYCons.constant = 0 - delta;
        // 修改头部视图的高度
        CGFloat viewH = IPhoneX ? 172 : 128;
        CGFloat headH = viewH - delta;
        if (headH < kHeadViewMinH) {
            headH = kHeadViewMinH;
        }
        //    self.headerView.height = headH;
        // 处理导航条
        // 计算当前的透明度
        CGFloat alpha = delta / (viewH - kHeadViewMinH);
        
        if (alpha > 1) {
            alpha = 1;
        }
        
        //
        //
        //
        if (alpha == 1) {
            [self.leftBtn setImage:[UIImage imageNamed:@"good_back_12x22_"] forState:UIControlStateNormal];
            [self.leftBtn setImage:[UIImage imageNamed:@"good_back_12x22_"] forState:UIControlStateHighlighted];
            [self.rightBtn setImage:[UIImage imageNamed:@"good_share_18x22_"] forState:UIControlStateNormal];
            [self.rightBtn setImage:[UIImage imageNamed:@"good_share_18x22_"] forState:UIControlStateHighlighted];
        } else {
            [self.leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateNormal];
            [self.leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateHighlighted];
            [self.rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateNormal];
            [self.rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateHighlighted];
        }
        
        // 设置标题的文字颜色
        //    _titleLabel.textColor = [UIColor colorWithWhite:0 alpha:alpha];
        
        // 获取导航条的颜色
        //    UIColor *navColor = [UIColor colorWithWhite:1 alpha:alpha];
        
        self.navLineView.backgroundColor = colorWithA(226, 226, 226,alpha);
        
        
        // 设置标题的文字颜色
        self.titleLabel.textColor = [UIColor colorWithWhite:1 alpha:alpha];
        if (alpha == 1) {
            self.leftBtn.alpha = 1;
            self.rightBtn.alpha = 1;
        } else {
            self.leftBtn.alpha = 1 - alpha;
            self.rightBtn.alpha = 1- alpha;
        }
        
        
        UIColor *navColor = colorWithA(23, 77, 237, alpha);
        
        self.headerView.backgroundColor = navColor;
        
        // 设置导航条背景图片
        //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:navColor] forBarMetrics:UIBarMetricsDefault];
    }else{
        
        
        // 计算下最新偏移量和最初偏移量的差值
        // 就是用户滚动的区域
        CGFloat delta = offsetY - _oriOffsetY;
        
        // 移动头部视图
        //    _headViewYCons.constant = 0 - delta;
        // 修改头部视图的高度
        CGFloat headH = kHeadViewH - delta;
        if (headH < kHeadViewMinH) {
            headH = kHeadViewMinH;
        }
        //    self.headerView.height = headH;
        
        
        // 处理导航条
        // 计算当前的透明度
        CGFloat alpha = delta / (kHeadViewH - kHeadViewMinH);
        
        if (alpha > 1) {
            alpha = 1;
        }
        //
        //
        //
        if (alpha == 1) {
            [self.leftBtn setImage:[UIImage imageNamed:@"good_back_12x22_"] forState:UIControlStateNormal];
            [self.leftBtn setImage:[UIImage imageNamed:@"good_back_12x22_"] forState:UIControlStateHighlighted];
            [self.rightBtn setImage:[UIImage imageNamed:@"good_share_18x22_"] forState:UIControlStateNormal];
            [self.rightBtn setImage:[UIImage imageNamed:@"good_share_18x22_"] forState:UIControlStateHighlighted];
        } else {
            [self.leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateNormal];
            [self.leftBtn setImage:[UIImage imageNamed:@"goods_back_rev_32x32_"] forState:UIControlStateHighlighted];
            [self.rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateNormal];
            [self.rightBtn setImage:[UIImage imageNamed:@"goods_share_rev_32x32_"] forState:UIControlStateHighlighted];
        }
        
        // 设置标题的文字颜色
        //    _titleLabel.textColor = [UIColor colorWithWhite:0 alpha:alpha];
        
        // 获取导航条的颜色
        //    UIColor *navColor = [UIColor colorWithWhite:1 alpha:alpha];
        
        self.navLineView.backgroundColor = colorWithA(226, 226, 226,alpha);
        
        
        // 设置标题的文字颜色
        self.titleLabel.textColor = [UIColor colorWithWhite:1 alpha:alpha];
        if (alpha == 1) {
            self.leftBtn.alpha = 1;
            self.rightBtn.alpha = 1;
        } else {
            self.leftBtn.alpha = 1 - alpha;
            self.rightBtn.alpha = 1- alpha;
        }
        
        
        UIColor *navColor = colorWithA(23, 77, 237, alpha);
        
        self.headerView.backgroundColor = navColor;
        
        // 设置导航条背景图片
        //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:navColor] forBarMetrics:UIBarMetricsDefault];
        
    }
    
  
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if ([self.myTag isEqualToString:@"0"]) {
        self.myTag = @"1";
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
